//
//  VistaTipoVehiculosPicoYPlaca.m
//  Pico y placa
//
//  Created by Mario Franco on 12/13/12.
//  Copyright (c) 2012 Mario Franco. All rights reserved.
//

#import "VistaTipoVehiculosPicoYPlaca.h"
#import "SessionManager.h"
#import "TipoVehiculo.h"

@interface VistaTipoVehiculosPicoYPlaca ()
{
    SessionManager *principal;
}

@end

@implementation VistaTipoVehiculosPicoYPlaca
@synthesize ciudad;
@synthesize tabla;
@synthesize bannerView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    principal = [SessionManager darInstancia];
    self.navigationItem.title = ciudad.nombre;
	// Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [self moveBannerViewOffscreen];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [ciudad.tiposVehiculos count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    TipoVehiculo *v = [ciudad.tiposVehiculos objectAtIndex:[indexPath row]];
    
    cell.textLabel.text = v.tipo;
    cell.textLabel.font=[UIFont fontWithName:@"ArialMT" size:18];
    
    if([[principal darFavoritos] containsObject:v])
        cell.accessoryType=UITableViewCellAccessoryCheckmark;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    
    //Si no ha escogido el tipo de vehículo
    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone)
    {
        if([[principal darFavoritos] count] <20)
        {
            [[principal darFavoritos] addObject:[ciudad.tiposVehiculos objectAtIndex:[indexPath row]]];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType=UITableViewCellAccessoryCheckmark;
        }
        
        else
        {
            UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:@"No se puede agregar más vehículos" delegate:self cancelButtonTitle:@"Aceptar" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
            popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
            [popupQuery showInView:self.view];
        }
    }       
    
    //Si ya escogió el tipo de vehiculo
    else
    {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        
        BOOL termino = NO;
        TipoVehiculo *actual = [ciudad.tiposVehiculos objectAtIndex:[indexPath row]];
        for (int i=0; i<[[principal darFavoritos] count] && !termino; i++)
        {
            TipoVehiculo *aBuscar = [[principal darFavoritos] objectAtIndex:i];
                        
            if([aBuscar.tipo isEqualToString:actual.tipo] && [aBuscar.ciudad.nombre isEqualToString:actual.ciudad.nombre])
            {
                
                if([aBuscar isEqual:[principal darFavorito]])
                    [principal establecerFavorito:[[TipoVehiculo alloc]init]];
                
                [[principal darFavoritos] removeObject:aBuscar];
                termino = YES;
            }        
        }
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)moveBannerViewOffscreen
{
    //Hacer que la subvista1 ocupe el espacio dejado por el bannerView
    CGRect frameOriginalTabla = tabla.frame;
    CGFloat nuevoHeight = self.view.frame.size.height;
    CGRect frameNuevoTabla = frameOriginalTabla;
    frameNuevoTabla.size.height = nuevoHeight;
    
    //Posicionar el bannerView debajo de la subvista1 (offscreen)
    CGRect frameNuevoBanner = bannerView.frame;
    frameNuevoBanner.origin.y = nuevoHeight;
    
    tabla.frame = frameNuevoTabla;
    bannerView.frame = frameNuevoBanner;
}

-(void)moveBannerViewOnscreen
{
    CGRect frameNuevoBanner = bannerView.frame;
    frameNuevoBanner.origin.y = self.view.frame.size.height - frameNuevoBanner.size.height;
    
    CGRect frameOriginalTabla = tabla.frame;
    CGFloat nuevoHeight = self.view.frame.size.height - frameNuevoBanner.size.height;
    CGRect frameNuevoTabla = frameOriginalTabla;
    frameNuevoTabla.size.height = nuevoHeight;
    
    [UIView beginAnimations:@"BannerViewIntro" context:NULL];
    tabla.frame = frameNuevoTabla;
    bannerView.frame = frameNuevoBanner;
    [UIView commitAnimations];
}

-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    [self moveBannerViewOffscreen];
}

-(void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    [self moveBannerViewOnscreen];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [bannerView removeFromSuperview];
    bannerView.delegate = nil;
    bannerView = nil;
}

@end
